package com.hanweb.service;

import com.alibaba.fastjson.JSON;
import com.hanweb.dto.IntegralDto;
import com.hanweb.utils.ContractOprUtil;
import lombok.extern.slf4j.Slf4j;
import org.hyperledger.fabric.gateway.Contract;
import org.hyperledger.fabric.gateway.ContractException;
import org.hyperledger.fabric.gateway.Transaction;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author Seven.Yin
 */
@Service
@Slf4j
public class ContractIntegralService {

    /**
     * 获取所有信息
     */
    public List<IntegralDto> getAllIntegrals() {
        try {
            Contract contract = ContractOprUtil.getContract();
            byte[] getAllIntegrals = contract.evaluateTransaction("GetAllIntegrals");
            return JSON.parseArray(new String(getAllIntegrals, StandardCharsets.UTF_8), IntegralDto.class);
        } catch (ContractException e) {
            log.error("获取所有信息失败=========>", e);
            return null;
        }
    }

    /**
     * 添加
     *
     * @param dto {@link IntegralDto}
     * @return contract return message
     */
    public IntegralDto create(IntegralDto dto) {
        IntegralDto integralDto = null;
        try {
            Transaction transaction = ContractOprUtil.transactionOfCreate("CreateIntegral");
            if (Objects.nonNull(transaction)) {
                byte[] submit = transaction.submit(
                        dto.getIntegralId(),
                        dto.getUserId(),
                        dto.getEventId(),
                        dto.getType(),
                        String.valueOf(dto.getNumber()),
                        dto.getCreateDate());
                log.info("新增返回数据====>{}", new String(submit, StandardCharsets.UTF_8));
                integralDto = JSON.parseObject(new String(submit, StandardCharsets.UTF_8), IntegralDto.class);
            }
        } catch (Exception e) {
            log.error("新增失败===============>", e);
        }

        return integralDto;
    }

    /**
     * 单个查询
     *
     * @param integralId id
     * @return {@link IntegralDto}
     */
    public IntegralDto queryOne(String integralId) {
        IntegralDto integralDto = null;
        try {
            Contract contract = ContractOprUtil.getContract();
            byte[] readIntegral = contract.createTransaction("ReadIntegral").submit(integralId);
            log.info("新增返回数据====>{}", new String(readIntegral, StandardCharsets.UTF_8));
            integralDto = JSON.parseObject(new String(readIntegral, StandardCharsets.UTF_8), IntegralDto.class);

        } catch (Exception e) {
            log.error("单个查询失败=======>", e);
        }
        return integralDto;
    }

    /**
     * 更新
     *
     * @param dto {@link IntegralDto}
     * @return {@link IntegralDto}
     */
    public IntegralDto update(IntegralDto dto) {
        IntegralDto integralDto = null;
        try {
            Transaction transaction = ContractOprUtil.transactionOfCreate("UpdateIntegral");
            if (Objects.nonNull(transaction)) {
                byte[] submit = transaction.submit(
                        dto.getIntegralId(),
                        dto.getUserId(),
                        dto.getEventId(),
                        dto.getType(),
                        String.valueOf(dto.getNumber()),
                        dto.getCreateDate());
                log.info("更新返回数据====>{}", new String(submit, StandardCharsets.UTF_8));
                integralDto = JSON.parseObject(new String(submit, StandardCharsets.UTF_8), IntegralDto.class);

            }
        } catch (Exception e) {
            log.error("更新失败=======>", e);
        }
        return integralDto;
    }

    /**
     * 删除
     *
     * @param integralId id
     * @return true or false
     */
    public boolean deleteIntegral(String integralId) {
        boolean flag = true;
        try {
            Transaction transaction = ContractOprUtil.transactionOfCreate("DeleteIntegral");
            if (Objects.nonNull(transaction)) {
                transaction.submit(integralId);
            }
        } catch (Exception e) {
            log.error("删除失败=======>", e);
            flag = false;
        }
        return flag;
    }

    /**
     * 根据key查询历史数据
     *
     * @param key key
     * @return history data
     */
    public List<Map<String, Object>> getHistoryDataByKey(String key) {
        List<Map<String, Object>> integralDtoList = new ArrayList<>();
        try {
            Contract contract = ContractOprUtil.getContract();
            byte[] getAllIntegrals = contract.createTransaction("GetHistoryByKey").submit(key);
            integralDtoList = JSON.parseObject(new String(getAllIntegrals, StandardCharsets.UTF_8), List.class);

        } catch (Exception e) {
            log.error("根据key查询历史数据错误=======>", e);
        }
        return integralDtoList;
    }

    /**
     * 测试-查询ClientIdentity内容
     *
     * @return ClientIdentity
     */
    public String getClientIdentity() {
        String clientIdentity = "";
        try {
            Contract contract = ContractOprUtil.getContract();
            byte[] getClientIdentity = contract.evaluateTransaction("GetClientIdentity");
            clientIdentity = new String(getClientIdentity, StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("测试-查询ClientIdentity内容失败==========>", e);
        }
        return clientIdentity;
    }
}
